from flask import Blueprint, jsonify, request
from app.models.models import db, Match, Team
from datetime import datetime, timedelta
from sqlalchemy import func, desc
import calendar
import json

matches = Blueprint('matches', __name__)

@matches.route('/api/matches', methods=['GET'])
def get_matches():
    matches = Match.query.order_by(Match.match_date.desc()).all()
    return jsonify([{
        'id': match.id,
        'team1': match.team1.name if match.team1 else '未知战队',
        'team2': match.team2.name if match.team2 else '未知战队',
        'winner': match.winner.name if match.winner else '未知战队',
        'investment': match.investment,
        'return_amount': match.return_amount,
        'profit': match.profit,
        'match_date': match.match_date.strftime('%Y-%m-%d'),
        'match_format': match.match_format,
        'team1_blue_side': match.team1_blue_side,
        'total_games': match.total_games,
        'games_json': match.games_json,
        'games': json.loads(match.games_json).get('games', []) if match.games_json else []
    } for match in matches])

@matches.route('/api/matches', methods=['POST'])
def create_match():
    data = request.get_json()
    
    # 确保数值字段是数字
    try:
        investment = float(data.get('investment', 0))
        return_amount = float(data.get('return_amount', 0))
    except (ValueError, TypeError):
        return jsonify({"message": "投资额和回报额必须是数字"}), 400
    
    # 确保布尔值正确解析
    if isinstance(data.get('team1_blue_side'), str):
        team1_blue_side = data.get('team1_blue_side').lower() == 'true'
    else:
        team1_blue_side = data.get('team1_blue_side', True)
    
    # 获取战队（必须已存在）
    team1 = Team.query.filter_by(name=data['team1']).first_or_404(description=f"主队 {data['team1']} 不存在")
    team2 = Team.query.filter_by(name=data['team2']).first_or_404(description=f"客队 {data['team2']} 不存在")
    
    # 确定获胜方
    winner = team1 if data['winner'] == data['team1'] else team2
    
    # 更新战队统计
    team1.total_matches += 1
    team2.total_matches += 1
    if winner == team1:
        team1.wins += 1
    else:
        team2.wins += 1
    
    # 处理游戏详情JSON
    games_data = data.get('games', [])
    games_json = {"games": games_data}
    
    # 确定总局数
    total_games = len(games_data) if games_data else (5 if data.get('match_format') == 'Bo5' else 3)
    
    # 计算利润
    profit = return_amount - investment
    
    # 创建比赛记录
    match = Match(
        game_type=data.get('game_type', 'lol'),
        team1_id=team1.id,
        team2_id=team2.id,
        winner_id=winner.id,
        investment=investment,
        return_amount=return_amount,
        profit=profit,
        match_date=parse_date_string(data.get('match_date')) if 'match_date' in data else datetime.utcnow(),
        match_format=data.get('match_format', 'Bo3'),
        team1_blue_side=team1_blue_side,
        total_games=total_games,
        games_json=json.dumps(games_json)
    )
    
    db.session.add(match)
    db.session.commit()
    
    return jsonify({
        'id': match.id,
        'team1': match.team1.name if match.team1 else '未知战队',
        'team2': match.team2.name if match.team2 else '未知战队',
        'winner': match.winner.name if match.winner else '未知战队',
        'investment': match.investment,
        'return_amount': match.return_amount,
        'profit': match.profit,
        'match_date': match.match_date.strftime('%Y-%m-%d'),
        'match_format': match.match_format,
        'team1_blue_side': match.team1_blue_side,
        'total_games': match.total_games,
        'games': json.loads(match.games_json).get('games', []) if match.games_json else []
    }), 201

def parse_date_string(date_string):
    """解析多种格式的日期字符串"""
    if not date_string:
        return datetime.utcnow()
    
    try:
        # 尝试ISO格式 (datetime-local输入, 例如: "2025-04-03T17:55")
        if 'T' in date_string:
            return datetime.fromisoformat(date_string)
        # 尝试日期格式 (例如: "2025-04-03")
        else:
            return datetime.strptime(date_string, '%Y-%m-%d')
    except ValueError:
        # 如果解析失败，返回当前时间
        return datetime.utcnow()

@matches.route('/api/matches/stats', methods=['GET'])
def get_stats():
    # 获取时间范围参数
    time_range = request.args.get('timeRange', 'all')
    
    # 基于时间范围过滤比赛
    query = Match.query
    
    today = datetime.now()
    if time_range == 'week':
        # 计算本周的开始（周一）
        start_of_week = today - timedelta(days=today.weekday())
        start_of_week = start_of_week.replace(hour=0, minute=0, second=0, microsecond=0)
        query = query.filter(Match.match_date >= start_of_week)
    elif time_range == 'month':
        # 计算本月的开始
        start_of_month = today.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
        query = query.filter(Match.match_date >= start_of_month)
    
    # 获取过滤后的比赛
    matches = query.all()
    
    # 计算总盈利（包括总局和单局）
    total_profit = 0
    total_matches = 0
    total_wins = 0
    
    for match in matches:
        # 计算总局盈利
        match_profit = match.return_amount - match.investment
        total_profit += match_profit
        total_matches += 1
        if match_profit > 0:
            total_wins += 1
            
        # 计算单局盈利
        if match.games_json:
            games = json.loads(match.games_json).get('games', [])
            for game in games:
                game_profit = game.get('return_amount', 0) - game.get('investment', 0)
                total_profit += game_profit
                total_matches += 1
                if game_profit > 0:
                    total_wins += 1
    
    # 计算胜率
    win_rate = round((total_wins / total_matches * 100) if total_matches > 0 else 0)
    
    # 计算每周的盈利数据
    weekly_profits = calculate_weekly_profits(time_range)
    
    # 获取战队表现数据
    team_performance = get_team_performance(time_range)
    
    return jsonify({
        'total_profit': total_profit,
        'total_matches': total_matches,
        'win_rate': win_rate,
        'weekly_profits': weekly_profits,
        'team_performance': team_performance
    })

def calculate_weekly_profits(time_range):
    """计算每周的盈利数据"""
    today = datetime.now()
    
    # 确定查询的时间范围
    if time_range == 'week':
        # 当前周
        start_date = today - timedelta(days=today.weekday())
        days_count = 7
    elif time_range == 'month':
        # 当前月
        start_date = today.replace(day=1)
        days_count = calendar.monthrange(today.year, today.month)[1]
    else:
        # 默认显示最近7天
        start_date = today - timedelta(days=6)
        days_count = 7
    
    start_date = start_date.replace(hour=0, minute=0, second=0, microsecond=0)
    
    # 初始化结果数组
    daily_profits = [0] * days_count
    
    # 按日期分组查询每天的盈利总和
    if time_range == 'week':
        # 查询本周每天的盈利
        for i in range(days_count):
            day_date = start_date + timedelta(days=i)
            next_day = day_date + timedelta(days=1)
            day_matches = Match.query.filter(
                Match.match_date >= day_date,
                Match.match_date < next_day
            ).all()
            
            day_profit = sum(match.return_amount - match.investment for match in day_matches)
            daily_profits[i] = day_profit
    elif time_range == 'month':
        # 按周汇总本月的数据
        weeks_in_month = (days_count + 6) // 7  # 向上取整，确保覆盖整个月
        weekly_profits = [0] * weeks_in_month
        
        for i in range(days_count):
            day_date = start_date + timedelta(days=i)
            next_day = day_date + timedelta(days=1)
            day_matches = Match.query.filter(
                Match.match_date >= day_date,
                Match.match_date < next_day
            ).all()
            
            day_profit = sum(match.return_amount - match.investment for match in day_matches)
            week_index = i // 7  # 确定属于哪一周
            weekly_profits[week_index] += day_profit
        
        return weekly_profits
    else:
        # 最近7天
        for i in range(days_count):
            day_date = today - timedelta(days=days_count-1-i)
            day_date = day_date.replace(hour=0, minute=0, second=0, microsecond=0)
            next_day = day_date + timedelta(days=1)
            
            day_matches = Match.query.filter(
                Match.match_date >= day_date,
                Match.match_date < next_day
            ).all()
            
            day_profit = sum(match.return_amount - match.investment for match in day_matches)
            daily_profits[i] = day_profit
    
    return daily_profits

def get_team_performance(time_range):
    """获取战队表现数据"""
    # 确定时间范围
    query = Match.query
    today = datetime.now()
    
    if time_range == 'week':
        start_of_week = today - timedelta(days=today.weekday())
        start_of_week = start_of_week.replace(hour=0, minute=0, second=0, microsecond=0)
        query = query.filter(Match.match_date >= start_of_week)
    elif time_range == 'month':
        start_of_month = today.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
        query = query.filter(Match.match_date >= start_of_month)
    
    # 获取所有战队
    teams = Team.query.all()
    team_stats = {}
    
    # 初始化战队统计数据
    for team in teams:
        team_stats[team.id] = {
            'id': team.id,
            'name': team.name,
            'league': team.league,
            'total_matches': 0,
            'wins': 0,
            'profit': 0
        }
    
    # 获取所有比赛记录
    matches = query.all()
    
    # 统计每个战队的表现
    for match in matches:
        # 主队参与的比赛
        if match.team1_id in team_stats:
            team_stats[match.team1_id]['total_matches'] += 1
            
            # 计算总局盈利
            match_profit = match.return_amount - match.investment
            team_stats[match.team1_id]['profit'] += match_profit
            if match_profit > 0:
                team_stats[match.team1_id]['wins'] += 1
                
            # 计算单局盈利
            if match.games_json:
                games = json.loads(match.games_json).get('games', [])
                for game in games:
                    if game.get('blue_team') == match.team1.name or game.get('red_team') == match.team1.name:
                        game_profit = game.get('return_amount', 0) - game.get('investment', 0)
                        team_stats[match.team1_id]['profit'] += game_profit
                        team_stats[match.team1_id]['total_matches'] += 1
                        if game_profit > 0:
                            team_stats[match.team1_id]['wins'] += 1
        
        # 客队参与的比赛
        if match.team2_id in team_stats:
            team_stats[match.team2_id]['total_matches'] += 1
            
            # 计算总局盈利
            match_profit = match.return_amount - match.investment
            team_stats[match.team2_id]['profit'] += match_profit
            if match_profit > 0:
                team_stats[match.team2_id]['wins'] += 1
                
            # 计算单局盈利
            if match.games_json:
                games = json.loads(match.games_json).get('games', [])
                for game in games:
                    if game.get('blue_team') == match.team2.name or game.get('red_team') == match.team2.name:
                        game_profit = game.get('return_amount', 0) - game.get('investment', 0)
                        team_stats[match.team2_id]['profit'] += game_profit
                        team_stats[match.team2_id]['total_matches'] += 1
                        if game_profit > 0:
                            team_stats[match.team2_id]['wins'] += 1
    
    # 转换为列表并计算胜率
    results = []
    for team_id, stats in team_stats.items():
        if stats['total_matches'] > 0:  # 只返回有比赛记录的战队
            win_rate = round((stats['wins'] / stats['total_matches'] * 100) if stats['total_matches'] > 0 else 0)
            results.append({
                'id': stats['id'],
                'name': stats['name'],
                'league': stats['league'],
                'total_matches': stats['total_matches'],
                'wins': stats['wins'],
                'win_rate': win_rate,
                'profit': stats['profit']
            })
    
    # 按盈利排序
    results.sort(key=lambda x: x['profit'], reverse=True)
    return results

@matches.route('/api/matches/<int:match_id>', methods=['PUT'])
def update_match(match_id):
    try:
        match = Match.query.get_or_404(match_id)
        data = request.get_json()

        # 更新比赛基本信息
        if 'match_date' in data:
            try:
                # 尝试解析带T的ISO格式
                if 'T' in data['match_date']:
                    match.match_date = datetime.strptime(data['match_date'], '%Y-%m-%dT%H:%M')
                # 尝试解析普通日期格式
                else:
                    match.match_date = datetime.strptime(data['match_date'], '%Y-%m-%d')
            except ValueError:
                # 如果解析失败，返回错误
                return jsonify({'error': '日期格式无效'}), 400

        if 'team1' in data:
            team1 = Team.query.filter_by(name=data['team1']).first_or_404(description=f"主队 {data['team1']} 不存在")
            match.team1_id = team1.id
        if 'team2' in data:
            team2 = Team.query.filter_by(name=data['team2']).first_or_404(description=f"客队 {data['team2']} 不存在")
            match.team2_id = team2.id
        if 'winner' in data:
            winner = Team.query.filter_by(name=data['winner']).first_or_404(description=f"获胜方 {data['winner']} 不存在")
            match.winner_id = winner.id
        if 'investment' in data:
            match.investment = float(data['investment'])
        if 'return_amount' in data:
            match.return_amount = float(data['return_amount'])
        if 'team1_blue_side' in data:
            match.team1_blue_side = data['team1_blue_side'] in [True, 'true', 1, '1']
        if 'games' in data:
            # 处理游戏详情
            games_data = data['games']
            games_json = {"games": games_data}
            match.games_json = json.dumps(games_json)
            # 更新总游戏数
            match.total_games = len(games_data)
            # 计算总利润
            match.profit = match.return_amount - match.investment

        db.session.commit()
        return jsonify({'message': '比赛记录更新成功'})
    except Exception as e:
        db.session.rollback()
        print('Error updating match:', str(e))  # 添加错误日志
        return jsonify({'error': f'更新失败：{str(e)}'}), 500

@matches.route('/api/matches/<int:match_id>', methods=['DELETE'])
def delete_match(match_id):
    match = Match.query.get_or_404(match_id)
    
    # 更新战队统计
    team1 = Team.query.get(match.team1_id)
    team2 = Team.query.get(match.team2_id)
    winner = Team.query.get(match.winner_id)
    
    if team1:
        team1.total_matches -= 1
    if team2:
        team2.total_matches -= 1
    
    if winner and winner.id == team1.id:
        team1.wins -= 1
    elif winner and winner.id == team2.id:
        team2.wins -= 1
    
    # 删除比赛记录
    db.session.delete(match)
    db.session.commit()
    
    return jsonify({'message': '比赛记录已删除'}), 200 